package io.example.router;

import io.example.common.utils.HttpUtils;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/3/9.
 */
public class HttpServerVerticle extends AbstractVerticle {

    private static final Logger logger = LoggerFactory.getLogger(HttpServerVerticle.class);

    public void start(Future<Void> startFuture) throws Exception {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        router.get("/").handler(this::indexHandler);
        router.post().handler(BodyHandler.create());
        router.post("/selectAll").handler(this::selectAllHandler);
        router.delete().handler(BodyHandler.create());
        router.delete("/").handler(this::deleteHandler);
        router.put().handler(BodyHandler.create());
        router.put("/").handler(this::saveHandler);
        server.requestHandler(router::accept) //绑定路由
                .listen(config().getInteger("http.server.port"), ar -> {    //监听端口
                    if (ar.succeeded()) {
                        logger.info("HTTP服务器启动，端口号： " + config().getInteger("http.server.port"));
                        startFuture.complete();
                    } else {
                        logger.error("无法启动HTTP服务器", ar.cause());
                        startFuture.fail(ar.cause());
                    }
                });
    }

    private void indexHandler(RoutingContext context) {
        HttpUtils.fireTextResponse(context, "Hello world");
    }

    private void selectAllHandler(RoutingContext context) {
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("action", "selectAll");
        JsonObject request = new JsonObject();
        vertx.eventBus().send("demo.dao", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                HttpServerResponse response = context.response();
                HttpUtils.fireJsonResponse(response, 200, body.mapTo(Map.class));
            } else {
                context.fail(reply.cause());
            }
        });
    }

    private void deleteHandler(RoutingContext context) {
        String id = context.getBodyAsJson().getString("id");
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("action", "delete");
        JsonObject request = new JsonObject();
        request.put("id", id);
        vertx.eventBus().send("demo.dao", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                Map<String, Object> resultMap = new HashMap<>();
                if (body.containsKey("count") && body.getInteger("count") > 0) {
                    resultMap.put("result", "success");
                } else {
                    resultMap.put("result", "failed");
                }
                HttpServerResponse response = context.response();
                HttpUtils.fireJsonResponse(response, 200, resultMap);
            } else {
                context.fail(reply.cause());
            }
        });
    }

    private void saveHandler(RoutingContext context) {
        JsonObject request = context.getBodyAsJson();
        DeliveryOptions options = new DeliveryOptions();
        options.addHeader("action", "save");
        vertx.eventBus().send("demo.dao", request, options, reply -> {
            if (reply.succeeded()) {
                JsonObject body = (JsonObject) reply.result().body();
                Map<String, Object> resultMap = new HashMap<>();
                if (body.containsKey("count") && body.getInteger("count") > 0) {
                    resultMap.put("result", "success");
                    if (body.containsKey("primaryKey")) {
                        resultMap.put("primaryKey", body.getValue("primaryKey"));
                    }
                } else {
                    resultMap.put("result", "failed");
                }
                HttpServerResponse response = context.response();
                HttpUtils.fireJsonResponse(response, 200, resultMap);
            } else {
                context.fail(reply.cause());
            }
        });
    }
}
